/*
 * @Author: 快的
 * @Description: 出码工具自动生成，不允许修改此部分注释
 * @pageUuid: f28bb9b4-322c-422e-8f33-4440094cbdf2
 * @file: nkfe.shouquanguanli/app/src/nodes/person-list-manage/index.tsx
 */
import React, { useState, useEffect, useRef, ElementRef } from 'react';
import M from '@block/utils';
import {
  Container,
  Button,
  Form,
  Select,
  notification,
  Upload,
  AsyncButton,
  Tooltip,
  Filelist,
  Loading,
  message,
} from '@block/plug';
import { Tabs, Modal, Input } from '@ss/mtd-react';
import { fetchUserInfo, MenuCode, LimitsAuthority } from '@src/utils';
import { PersonManageRecords } from './elements/index';
import { TabStatus, TabCode, TabCountData } from './type';
import URL from './url';
import './index.scss';

const { Header, Main } = Container;

/** 导入文件类型 */
interface CustomFile extends File {
  /** 文件url地址 */
  url?: string;
}

// 导入模板资源地址
const ImportTemplatesUrl =
  'https://s3plus.meituan.net/nk-s3/%E5%90%8D%E5%8D%95%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx';

/**
 * 名单管理菜单
 */
const PersonListManage = () => {
  /** state 定义 */
  const [tabCountData, setTabCountData] = useState<TabCountData>(); // tab角标数字
  const [pageActions, setPageActions] = useState<Array<LimitsAuthority>>([]); // 页面操作权限
  const [activeTab, setActiveTab] = useState<TabCode>('All'); // 当前激活tab
  const [importModalVisible, setImportModalVisible] = useState<boolean>(false); // 导入弹窗显示状态
  const [createModalVisible, setCreateModalVisible] = useState<boolean>(false); // 新建弹窗显示状态
  const [uploadLoading, setUploadLoading] = useState<boolean>(false); // 导入的loading状态
  const [uploadFileList, setUploadFileList] = useState<CustomFile[]>([]); // 导入上传文件

  /** ref 定义 */
  const createFormRef = useRef<Form>(null); // 新建表单form实例
  const personManageRecordsRef = useRef<ElementRef<typeof PersonManageRecords>>(null); // 新建表单form实例
  const submitFormRef = useRef<Form>(null); // 全部提交弹窗里form实例

  /** this 定义 */
  const userInfoThis = useRef(null); // 用户信息this对象

  // tabs配置信息
  const tabsConfig = [
    { key: 'All', name: '全部', count: tabCountData?.allStatusCount },
    { key: 'NeedSubmit', name: '待提交', count: tabCountData?.needSubmitStatusCount },
    { key: 'Audit', name: '审批中', count: tabCountData?.auditStatusCount },
    { key: 'Valid', name: '生效中', count: tabCountData?.validStatusCount },
    { key: 'Invalid', name: '已失效', count: tabCountData?.invalidStatusCount },
  ];

  /** 获取各状态下数据量 */
  const getStatusCount = async () => {
    const res = await M.$fetch<TabCountData>(URL.countByStatus);
    setTabCountData(res);
  };

  /** 获取页面初始化数据 */
  const getInitData = async () => {
    userInfoThis.current = await fetchUserInfo();
    const res = await M.$fetch<Array<LimitsAuthority>>(URL.queryPermissionListByMenu, {
      menuCode: MenuCode.senPosPersonListManage,
    });
    setPageActions(res || []);
  };

  /** DidMount */
  useEffect(() => {
    getStatusCount();
    getInitData();
  }, []);

  /**
   * 创建人员确认按钮处理
   * @param e event
   * @param btn 按钮实例
   */
  const handleCreateOK = async (e: MouseEvent, btn: Button) => {
    if (createFormRef.current.validateFields()) {
      try {
        btn.loading(true);
        const params = createFormRef.current?.getFieldsValue();
        params.empIdList = params?.empIdList?.map((item) => item?.code);
        params.sensitivePosTypeList = params?.sensitivePosTypeList?.map((item) => item?.code);
        const res = await M.$fetch<OperateResponse>(URL.addPersonList, params);
        notification.success({ title: '成功', message: res?.message || '这是一条成功消息通知' });
        setCreateModalVisible(false);
        personManageRecordsRef.current?.recordsSearch();
        getStatusCount();
      } finally {
        btn.loading(false);
      }
    }
  };

  /** 导出处理 */
  const handleExport = async () => {
    const params = personManageRecordsRef.current?.getFilterValue();
    const res = await M.$fetch<OperateResponse>(URL.exportPersonList, params);
    notification.success({ title: '成功', message: res.message || '操作成功' });
  };

  /**
   * 处理导入的提交
   * @param e event
   * @param btn 按钮实例
   */
  const handleUploadSubmit = (e: MouseEvent, btn: Button) => {
    if (uploadFileList.length === 0) {
      message.error({ message: '请上传导入文件' });
    } else {
      btn.loading(true);
      setUploadLoading(true);
      const [file] = uploadFileList;
      Upload.helper.upload(URL.importPersonList, file, {
        onSuccess: (response) => {
          notification.success({ title: '成功', message: response.message || '导入完成，请注意大象消息查看导入结果' });
          setUploadLoading(false);
          setImportModalVisible(false);
          setUploadFileList([]);
          btn.loading(false);
        },
        onError: (error) => {
          notification.error({ title: '失败', message: error.message || '导入失败' });
          setUploadLoading(false);
          btn.loading(false);
        },
      });
    }
  };

  /**
   * 上传时校验文件大小
   * @param file 上传的文件
   * @returns 是否继续
   */
  const handleBeforeUpload = (file: File[]) => {
    const fileSize = Upload.helper.getFileSizeWithMB(file[0]);
    if (fileSize > 20) {
      message.error({ message: '上传文件最大20M' });
      return false;
    }
    return true;
  };

  return (
    <div className="person-list-manage">
      <Header className="person-list-manage-header" style={{ height: 'auto' }}>
        <div className="header-title">
          <span>名单管理</span>
        </div>
        <div className="header-btns">
          {['All', 'NeedSubmit', 'Valid', 'Invalid'].includes(activeTab) &&
            pageActions.includes(LimitsAuthority.export) && (
              <Tooltip message="导出查询结果全部数据" autoDestory>
                <Button onClick={handleExport} rightIcon="info-circle-o" type="normal">
                  导出
                </Button>
              </Tooltip>
            )}
          {['All', 'NeedSubmit', 'Valid'].includes(activeTab) && pageActions.includes(LimitsAuthority.import) && (
            <Button onClick={() => setImportModalVisible(true)} type="normal">
              导入
            </Button>
          )}
          {['All', 'NeedSubmit', 'Valid'].includes(activeTab) && pageActions.includes(LimitsAuthority.add) && (
            <Button onClick={() => setCreateModalVisible(true)} type="primary">
              新建
            </Button>
          )}
          {false && ['NeedSubmit', 'Valid'].includes(activeTab) && pageActions.includes(LimitsAuthority.submitAll) && (
            <Tooltip message='提交审批所有"待提交"状态的名单' autoDestory>
              <Button
                onClick={() => {
                  Modal.confirm({
                    title: '全部提交',
                    message: (
                      <Form ref={submitFormRef} labelWidth="120px" labelPosition="right" labelInValue={false}>
                        <Form.Item formItemKey="custom_f71" label="提交说明：" span={24}>
                          <Input.TextArea showCount toFormItem />
                        </Form.Item>
                      </Form>
                    ),
                    onOk: () => {
                      if (submitFormRef.current.validateFields()) {
                        // 发送一个请求
                      }
                      return true;
                    },
                    onCancel: () => {},
                  });
                }}
                type="primary"
                rightIcon="info-circle-o"
              >
                全部提交
              </Button>
            </Tooltip>
          )}
        </div>
      </Header>
      <Main className="person-list-manage-main">
        <Tabs
          autoDestory
          activeKey={activeTab}
          onChange={(activeKey: TabCode) => {
            getStatusCount();
            setActiveTab(activeKey);
          }}
        >
          {tabsConfig.map((tab) => {
            return (
              <Tabs.TabPane
                key={tab.key}
                label={
                  <span>
                    <span>{tab.name}</span>
                    {!!tab.count && <span>({tab.count})</span>}
                  </span>
                }
              >
                <PersonManageRecords
                  ref={personManageRecordsRef}
                  tabStatus={TabStatus[tab.key]}
                  pageActions={pageActions}
                  getStatusCount={getStatusCount}
                />
              </Tabs.TabPane>
            );
          })}
        </Tabs>
      </Main>
      {importModalVisible && (
        <Modal
          title="导入数据"
          closable
          onClose={() => {
            setImportModalVisible(false);
            setUploadFileList([]);
          }}
          style={{ width: '460px' }}
        >
          <Modal.Body>
            <Loading loading={uploadLoading}>
              <Upload
                accept=".xlsx"
                onBeforeUpload={handleBeforeUpload}
                onUpload={(file: CustomFile) => setUploadFileList([file])}
              >
                <Button type="grey">选择文件</Button>
              </Upload>
              <span className="person-list-manage-import-text">仅支持导入xlsx格式文档</span>
              <Button
                shape="text"
                type="primary"
                onClick={() => {
                  window.open(ImportTemplatesUrl);
                }}
              >
                下载模板
              </Button>
              <Filelist style={{ width: 366, marginTop: '10px' }}>
                {uploadFileList.map((item) => {
                  let fileSize = Upload.helper.getFileSizeWithMB(item);
                  let unit = 'MB';
                  if (fileSize < 1) {
                    fileSize = Upload.helper.getFileSizeWithKB(item);
                    unit = 'KB';
                  }
                  return (
                    <Filelist.Item
                      key={item?.lastModified}
                      name={item?.name}
                      onRemove={() => setUploadFileList([])}
                      info={
                        <>
                          <span style={{ marginRight: '10px' }}>{`${fileSize.toFixed(1)}${unit}`}</span>
                          <span style={{ marginRight: '10px' }}>
                            {userInfoThis.current?.name}/{userInfoThis.current?.misNo}
                          </span>
                          {item?.lastModified && (
                            <span style={{ marginRight: '10px' }}>
                              {M.datejs(item.lastModified).format('YYYY-MM-DD')}
                            </span>
                          )}
                        </>
                      }
                    />
                  );
                })}
              </Filelist>
            </Loading>
          </Modal.Body>
          <Modal.Footer>
            <Button
              style={{ marginRight: '12px' }}
              onClick={() => {
                setImportModalVisible(false);
                setUploadFileList([]);
              }}
            >
              取消
            </Button>
            <Button onClick={handleUploadSubmit} type="primary">
              确定
            </Button>
          </Modal.Footer>
        </Modal>
      )}
      {createModalVisible && (
        <Modal title="新建人员" style={{ width: '600px' }} closable onClose={() => setCreateModalVisible(false)}>
          <Modal.Body>
            <Form ref={createFormRef} labelWidth="140px" labelPosition="right" labelInValue={false}>
              <Form.Item
                formItemKey="empIdList"
                label="人员："
                required
                span={24}
                rules={[
                  {
                    validator: (config, key, callback, data) => {
                      const { length } = data.empIdList || [];
                      if (length <= 0) {
                        callback('请填写必填信息');
                      } else if (length > 20) {
                        callback('已超出内容限制，最多可输入20个');
                      } else {
                        callback();
                      }
                    },
                  },
                ]}
              >
                <Select
                  keyField="code"
                  multiple
                  labelField="name"
                  placeholder="请输入姓名/Mis号"
                  dispatchFetchDataWithoutKeyword={false}
                  maxTagCount={5}
                  toFormItem
                  onFetchData={(search) =>
                    M.$fetch<SelectOption<string>[]>(URL.queryEmployeeList, { search: search?.trim() })
                  }
                />
              </Form.Item>
              <Form.Item
                formItemKey="sensitivePosTypeList"
                label="敏感信息岗位分类："
                span={24}
                required
                message="请填写必填信息"
              >
                <Select
                  keyField="code"
                  labelField="name"
                  multiple
                  filterable={false}
                  maxTagCount={5}
                  onFetchData={() => M.$fetch<SelectOption<string>[]>(URL.querySensitivePosTypeList)}
                  placeholder="请选择敏感岗位分类"
                  toFormItem
                />
              </Form.Item>
              <Form.Item formItemKey="riskDesc" label="风险描述：" span={24}>
                <Input.TextArea showCount placeholder="请输入风险描述" toFormItem maxLength="500" />
              </Form.Item>
            </Form>
          </Modal.Body>
          <Modal.Footer>
            <Button onClick={() => setCreateModalVisible(false)} style={{ marginRight: '12px' }}>
              取消
            </Button>
            <AsyncButton onClick={handleCreateOK} type="primary">
              确定
            </AsyncButton>
          </Modal.Footer>
        </Modal>
      )}
    </div>
  );
};

export default PersonListManage;
